﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using FrienDev.BusinessRules;
using FrienDev.Data;
using System.Collections.Generic;

public partial class Controls_Activity_Add : System.Web.UI.UserControl
{
    private int m_activityID = -1;
    private int m_clubID = -1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request["activityId"] != null)
        {
            m_activityID = Convert.ToInt32(HttpContext.Current.Request["activityId"]);
        }
        if (HttpContext.Current.Request["clubId"] == null)
        {
            if (HttpContext.Current.Request["activityId"] == null)
            {
                lb_Title.Text = "新建活动";

                drpClubList.Visible = true;
                pnClub.Visible = true;
                IEnumerable<Club> clubs = ClubRules.Instance.GetOwnClubByUserId(UserRules.Instance.GetCurrentUserId());
                if (clubs.Count() == 0)
                {
                    Response.Write("<script>alert('您首先需要成为一个俱乐部的成员');window.location.href='../home/default.aspx'</script>");
                }
                else
                {
                    drpClubList.DataSource = clubs;
                    drpClubList.DataTextField = "ClubName";
                    drpClubList.DataValueField = "ClubId";
                    drpClubList.DataBind();
                    drpClubList.SelectedIndex = 0;
                }
            }
            else
            {
                Activity activity = ActivityRules.Instance.GetActivityInfo(m_activityID);
                if (activity == null)
                {
                    HttpContext.Current.Response.Redirect("~/home/default.aspx");
                    return;
                }
                m_clubID = activity.ClubId;
            }
        }
        else
        {
            m_clubID = Convert.ToInt32(HttpContext.Current.Request["clubId"]);
            int userClubType = ClubRules.Instance.GetMemberTypeIdByUserIdAndClubId(m_clubID, UserRules.Instance.GetCurrentUserId());
            if (userClubType > ClubRules.m_3LevelMemberTypeId || userClubType < 0)//FixMe:
            {
                HttpContext.Current.Response.Redirect("~/home/default.aspx");
            }
            lb_Title.Text = "新建活动";

        }
        if (!IsPostBack)
        {
            drpProvince.SelectedIndexChanged += new EventHandler(drpProvince_SelectedIndexChanged);
            //drpStartMonth.SelectedIndexChanged += new EventHandler(drpMonthDateSelectChanged);
            //drpEndMonth.SelectedIndexChanged += new EventHandler(drpMonthDateSelectChanged);
            //drpDeadlineMonth.SelectedIndexChanged += new EventHandler(drpMonthDateSelectChanged);
            InitProvinceDropDownList();
            InitCityDropDownList();
            InitDateDropDownLists();

            if (m_activityID != -1)
            {
                if (!ActivityRules.Instance.IsCurrentUserIsActivityPromoter(m_activityID))
                    HttpContext.Current.Response.Redirect("~/home/default.aspx");
                FillActivityInfo(m_activityID);
                ControlsOnChanged(null, null);
            }

        }
        //TODO:判断club是否存在，或者在数据库访问抛出异常时进行相应判断

    }
    protected void bt_Save_Click(object sender, EventArgs e)
    {
        int t_activityId = -1;
        DateTime startDate = new DateTime(Convert.ToDateTime(txtStartDate.Text).Year,
             Convert.ToDateTime(txtStartDate.Text).Month,
             Convert.ToDateTime(txtStartDate.Text).Day,
                Convert.ToInt32(drpStartHour.SelectedValue),
                Convert.ToInt32(drpStartMinute.SelectedValue),
                0);
        DateTime deadlineDate = new DateTime(Convert.ToDateTime(txtDeadLineDate.Text).Year,
            Convert.ToDateTime(txtDeadLineDate.Text).Month,
            Convert.ToDateTime(txtDeadLineDate.Text).Day,
            Convert.ToInt32(drpDeadlineHour.SelectedValue),
            Convert.ToInt32(drpDeadlineMinute.SelectedValue),
            0);
        DateTime endDate = new DateTime(Convert.ToDateTime(txtEndDate.Text).Year,
            Convert.ToDateTime(txtEndDate.Text).Month,
            Convert.ToDateTime(txtEndDate.Text).Day,
           Convert.ToInt32(drpEndHour.SelectedValue),
           Convert.ToInt32(drpEndMinute.SelectedValue),
           0);

        if (drpClubList.Enabled)
        {
            m_clubID = Convert.ToInt32(drpClubList.SelectedValue);
        }

        int qq = 0;

        if (!int.TryParse(txtQQ.Text, out qq))
        {
            qq = 0;
        }

        if (m_activityID != -1 && ActivityRules.Instance.IsActivityExisted(m_activityID))
        {
            ActivityRules.Instance.UpdateActivity(m_activityID,
                txtName.Text.Trim(),
                startDate,
                endDate,
                txtDescription.Text.Trim(),
                Convert.ToInt32(rbActivityType.SelectedValue),
                txtSubject.Text.Trim(),
                rbTargetAudience.SelectedValue,
                deadlineDate,
                txtAddress.Text.Trim(),
                txtExpense.Text.Trim(),
                Convert.ToInt32(txtLimit.Text),
                txtPhone.Text.Trim(),
                txtEmail.Text.Trim(),
                txtMSN.Text.Trim(),
                qq,
                m_clubID,
                Convert.ToInt32(drpCity.SelectedValue),
                0,
                Convert.ToBoolean(rbIsNeedPermit.SelectedValue),
                Convert.ToBoolean(rbIsPublic.SelectedValue),
                Convert.ToInt32(txtSingleLimit.Text)
                );
        }
        else
        {
            t_activityId = ActivityRules.Instance.InsertActivity(
                txtName.Text.Trim(),
                startDate,
                endDate,
                txtDescription.Text.Trim(),
                Convert.ToInt32(rbActivityType.SelectedValue),
                txtSubject.Text.Trim(),
                rbTargetAudience.SelectedValue,
                deadlineDate,
                txtAddress.Text.Trim(),
                txtExpense.Text.Trim(),
                Convert.ToInt32(txtLimit.Text),
                txtPhone.Text.Trim(),
                txtEmail.Text.Trim(),
                txtMSN.Text.Trim(),
                qq,
                m_clubID,
                Convert.ToInt32(drpCity.SelectedValue),
                0,
                Convert.ToBoolean(rbIsNeedPermit.SelectedValue),
                Convert.ToBoolean(rbIsPublic.SelectedValue),
                Convert.ToInt32(txtSingleLimit.Text)
                );
            ActivityRules.Instance.InsertActivityPromoter(t_activityId, UserRules.Instance.GetCurrentUserId());
        }
        upAddActivity.Update();
        if (t_activityId != -1)
        {
            //Response.Redirect("/activity/activityEdit.aspx?clubid=" + m_clubID + "&activityid=" + t_activityId + "&show=feedback");
            Response.Redirect("/Activity/Detail.aspx?activityId=" + t_activityId);
        }
        else if (m_activityID != -1)
        {
            //Response.Redirect("/activity/activityEdit.aspx?clubid=" + m_clubID + "&activityid=" + m_activityID + "&show=feedback");
            Response.Redirect("/Activity/Detail.aspx?activityId=" + m_activityID);
        }
    }

    private void drpMonthDateSelectChanged(object sender, EventArgs e)
    {
        int currentmonth = Convert.ToInt32((sender as DropDownList).SelectedValue.ToString());
        if (currentmonth == 1 || currentmonth == 3 || currentmonth == 5 || currentmonth == 7 || currentmonth == 8 || currentmonth == 10 || currentmonth == 12)
        {
            InitDropDownList(sender as DropDownList, 1, 31);
        }
        else
        {
            InitDropDownList(sender as DropDownList, 1, 30);
        }
    }

    protected void drpProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        InitCityDropDownList();
    }

    private void FillActivityInfo(int activityID)
    {
        Activity activity = ActivityRules.Instance.GetActivityInfo(activityID);
        if (activity == null)
            return;
        txtAddress.Text = activity.Address;
        txtDescription.Text = activity.Description;
        txtEmail.Text = activity.Email;
        txtExpense.Text = activity.Expense;
        txtLimit.Text = activity.SignUpLimit.ToString();
        txtMSN.Text = activity.MSN;
        txtName.Text = activity.ActivityName;
        txtPhone.Text = activity.Phone;
        txtQQ.Text = activity.QQ.ToString();
        txtSingleLimit.Text = activity.SingleUserSignUpLimit.ToString();
        txtSubject.Text = activity.Subject;
        rbActivityType.SelectedValue = activity.ActivityType.ToString();
        rbIsNeedPermit.SelectedValue = activity.IsNeedPermission.ToString();
        rbIsPublic.SelectedValue = activity.IsPublic.ToString();
        rbTargetAudience.SelectedValue = activity.TargetAudience;
        //显示所属俱乐部
        pnClub.Visible = true;
        drpClubList.Items.Clear();
        drpClubList.Items.Add(activity.Club.ClubName);
        drpClubList.SelectedIndex = 0;
        drpClubList.Enabled = false;

        if (string.IsNullOrEmpty(activity.CityId.ToString()))
        {
            drpProvince.SelectedValue = "1";
            InitCityDropDownList();
            drpCity.SelectedValue = "1";
        }
        else
        {

            drpProvince.SelectedValue = UserRules.Instance.GetProvinceByCityId(Convert.ToInt32(activity.CityId.ToString())).ProvinceId.ToString();
            InitCityDropDownList();
            drpCity.SelectedValue = activity.CityId.ToString();
        }
        FillDropDownListDate("start", activity.BeginDateTime);
        FillDropDownListDate("end", activity.EndDateTime);
        FillDropDownListDate("deadline", activity.JoinDeadLine);
    }

    /// <summary>
    /// 初始化dropDownList
    /// </summary>
    private void InitDateDropDownLists()
    {
        //InitDropDownList(drpStartYear, 1900, Convert.ToInt32(DateTime.Now.Year.ToString()), true);
        //InitDropDownList(drpStartMonth, 1, 12);
        //InitDropDownList(drpStartDay, 1, 31);
        InitDropDownList(drpStartHour, 0, 23);
        InitDropDownList(drpStartMinute, 0, 59);
        //InitDropDownList(drpEndYear, 1900, Convert.ToInt32(DateTime.Now.Year.ToString()), true);
        //InitDropDownList(drpEndMonth, 1, 12);
        //InitDropDownList(drpEndDay, 1, 31);
        InitDropDownList(drpEndHour, 0, 23);
        InitDropDownList(drpEndMinute, 0, 59);
        //InitDropDownList(drpDeadlineYear, 1900, Convert.ToInt32(DateTime.Now.Year.ToString()), true);
        //InitDropDownList(drpDeadlineMonth, 1, 12);
        //InitDropDownList(drpDeadlineDay, 1, 31);
        InitDropDownList(drpDeadlineHour, 0, 23);
        InitDropDownList(drpDeadlineMinute, 0, 59);

        //drpStartYear.SelectedValue = DateTime.Now.Year.ToString();
        //drpEndYear.SelectedValue = DateTime.Now.Year.ToString();
        //drpDeadlineYear.SelectedValue = DateTime.Now.Year.ToString();

        //drpStartMonth.SelectedValue = DateTime.Now.Month.ToString();
        //drpEndMonth.SelectedValue = DateTime.Now.Month.ToString();
        //drpDeadlineMonth.SelectedValue = DateTime.Now.Month.ToString();

        //drpStartDay.SelectedValue = DateTime.Now.Day.ToString();
        //drpEndDay.SelectedValue = DateTime.Now.Day.ToString();
        //drpDeadlineDay.SelectedValue = DateTime.Now.Day.ToString();

        txtStartDate.Text = DateTime.Now.ToShortDateString();
        txtEndDate.Text = DateTime.Now.ToShortDateString();
        txtDeadLineDate.Text = DateTime.Now.ToShortDateString();


        drpStartHour.SelectedValue = DateTime.Now.Hour.ToString();
        drpEndHour.SelectedValue = DateTime.Now.Hour.ToString();
        drpDeadlineHour.SelectedValue = DateTime.Now.Hour.ToString();

        drpStartMinute.SelectedValue = DateTime.Now.Minute.ToString();
        drpEndMinute.SelectedValue = DateTime.Now.Minute.ToString();
        drpDeadlineMinute.SelectedValue = DateTime.Now.Minute.ToString();
    }

    /// <summary>
    /// 填充DateTime dropdownList
    /// </summary>
    /// <param name="type"></param>
    /// <param name="dateTime"></param>
    private void FillDropDownListDate(string type, DateTime dateTime)
    {
        if (type == "start")
        {
            txtStartDate.Text = dateTime.ToShortDateString();
            drpStartHour.SelectedValue = dateTime.Hour.ToString();
            drpStartMinute.SelectedValue = dateTime.Minute.ToString();
        }
        else if (type == "end")
        {
            txtEndDate.Text = dateTime.ToShortDateString();
            drpEndHour.SelectedValue = dateTime.Hour.ToString();
            drpEndMinute.SelectedValue = dateTime.Minute.ToString();
        }
        else if (type == "deadline")
        {
            txtDeadLineDate.Text = dateTime.ToShortDateString();
            drpDeadlineHour.SelectedValue = dateTime.Hour.ToString();
            drpDeadlineMinute.SelectedValue = dateTime.Minute.ToString();
        }
    }


    private void InitProvinceDropDownList()
    {
        drpProvince.DataSource = UserRules.Instance.GetProvinces();
        drpProvince.DataTextField = "ProvinceName";
        drpProvince.DataValueField = "ProvinceId";
        drpProvince.DataBind();
    }
    private void InitCityDropDownList()
    {
        drpCity.DataSource = UserRules.Instance.GetCitiesByProvinceId(Convert.ToInt32(drpProvince.SelectedValue.ToString()));
        drpCity.DataTextField = "CityName";
        drpCity.DataValueField = "CityId";
        drpCity.DataBind();
    }

    private void InitDropDownList(DropDownList drp, int startNum, int endNum)
    {
        drp.Items.Clear();
        for (int i = startNum; i <= endNum; i++)
        {
            ListItem item = new ListItem();
            item.Text = i.ToString();
            item.Value = i.ToString();
            drp.Items.Add(item);
        }
    }

    private void InitDropDownList(DropDownList drp, int startNum, int endNum, bool isYear)
    {
        if (isYear)
            endNum += 10;
        InitDropDownList(drp, startNum, endNum);
    }

    protected void ControlsOnChanged(object sender, EventArgs e)
    {
        DateTime startDate = new DateTime(Convert.ToDateTime(txtStartDate.Text).Year,
            Convert.ToDateTime(txtStartDate.Text).Month,
            Convert.ToDateTime(txtStartDate.Text).Day,
               Convert.ToInt32(drpStartHour.SelectedValue),
               Convert.ToInt32(drpStartMinute.SelectedValue),
               0);
        DateTime deadlineDate = new DateTime(Convert.ToDateTime(txtDeadLineDate.Text).Year,
            Convert.ToDateTime(txtDeadLineDate.Text).Month,
            Convert.ToDateTime(txtDeadLineDate.Text).Day,
            Convert.ToInt32(drpDeadlineHour.SelectedValue),
            Convert.ToInt32(drpDeadlineMinute.SelectedValue),
            0);
        DateTime endDate = new DateTime(Convert.ToDateTime(txtEndDate.Text).Year,
            Convert.ToDateTime(txtEndDate.Text).Month,
            Convert.ToDateTime(txtEndDate.Text).Day,
           Convert.ToInt32(drpEndHour.SelectedValue),
           Convert.ToInt32(drpEndMinute.SelectedValue),
           0);
        if (startDate < deadlineDate)
        {
            lblStartDateError.Visible = true;
            bt_Save.Enabled = false;
            upStartDate.Update();
        }
        else
        {
            lblStartDateError.Visible = false;
            bt_Save.Enabled = true;
            upStartDate.Update();
        }
        if (startDate > endDate)
        {
            lblEndDateError.Visible = true;
            bt_Save.Enabled = false;
            upEndDate.Update();
        }
        else
        {
            lblEndDateError.Visible = false;
            bt_Save.Enabled = true;
            upEndDate.Update();
        }
        upConfirm.Update();
    }
}
